var express = require("express");
var router = express.Router();
var jwt = require("jsonwebtoken");

// 验证身份令牌，实现无感刷新Token
const verifyAuthToken = (req, res, next) => {
    const accessToken = req.headers["authorization"];
    const refreshToken = req.headers["pass"];
    if (!accessToken) {
      return res.status(400).json({ msg: "身份令牌未提供！" });
    }
    jwt.verify(accessToken, "accessToken", (err, decoded) => {
      if (err) {
        if (err.name === "TokenExpiredError") {
          jwt.verify(refreshToken, "refreshToken", (err, decoded) => {
            if (err) {
              return res
                .status(403)
                .json({ msg: "refreshToken过期，请重新登录" });
            }
            let id = decoded.id;
            let newAccessToken = jwt.sign({ id }, "accessToken", {
              expiresIn: "6h",
            });
            let newRefreshToken = jwt.sign({ id }, "refreshToken", {
              expiresIn: "5d",
            });
            return res.status(401).json({
              accessToken: newAccessToken,
              refreshToken: newRefreshToken,
              msg: "新的令牌",
            });
          });
        }
        return res.status(400).json({ msg: "身份验证失败" });
      } else {
        req.user = decoded;
        next();
      }
    });
  };
   